package com.hbyj.util;

import java.util.Date;
import java.util.Vector;

import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

import com.hbyj.object.onLineUserObj;

public class OnLineUser implements HttpSessionBindingListener {
	private static Vector users=new Vector();
	private String ip="";
	
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}
	public int getCount(){
       users.trimToSize();//调整Vector users的容量为Vector users的大小
       return users.capacity();//返回users的容量
	}
	public  OnLineUser() {
		
	}
	/**
	 * author cuiyi
	 * time 2012-11-22
	 * disc 检测用户是否存在
	 * @param userName
	 * @return
	 */
	public boolean existUser(String userName){
	       users.trimToSize();
	       boolean existUser=false;
	       for (int i=0;i<users.capacity();i++ )
	       {
	           if (userName.equalsIgnoreCase(((onLineUserObj)users.get(i)).getUserId()))
	           {
	               existUser=true;
	               break;
	           }
	       }
	       return existUser;
	 }
	
	   /**
	 * author cuiyi
	 * time 2012-11-22
	 * disc 用户退出，删除信息
	 * @param userName
	 * @return
	 */
	public boolean deleteUser(String userName){
	       users.trimToSize();
	       if(existUser(userName)){
	           int currUserIndex=-1;
	           for(int i=0;i<users.capacity();i++){
	               if(userName.equalsIgnoreCase(((onLineUserObj)users.get(i)).getUserId())){
	                   currUserIndex=i;
	                   break;
	               }
	           }
	           if (currUserIndex!=-1){
	               users.remove(currUserIndex);
	               users.trimToSize();
	               return true;
	           }
	       }
	       return false;
   }
	   /**
	 * author cuiyi
	 * time 2012-11-22
	 * disc 得到所有在线用户
	 * @return
	 */
	public Vector getOnLineUser()
	   {
	       return users;
	   }
	   
	   public void valueBound(HttpSessionBindingEvent e){ 
	       	users.trimToSize();
		    if(!existUser(e.getName())){
		    	String ip = this.getIp();
		    	onLineUserObj obj = new onLineUserObj(this.getIp(),e.getName());
		        users.add(obj);
		    }
	   } 

	   public void valueUnbound(HttpSessionBindingEvent e){ 
		    users.trimToSize();
		    String userName=e.getName();
		    System.out.println(userName);
		    deleteUser(userName);
	   } 
	   public String getOnLineUserIpByName(String userName){
		   if(existUser(userName)){
	           for(int i=0;i<users.capacity();i++){
	               if(userName.equals(((onLineUserObj)users.get(i)).getUserId())){
	                   return ((onLineUserObj)users.get(i)).getIp();
	               }
	           }
	       }
		   return "0.0.0.0";
	   }
}
